from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from typing import Optional

from app.core.database import get_db
from app.core.deps import get_current_user
from app.schemas.tenant import (
    TenantCreate, TenantUpdate, TenantListResponse,
    UpdateStatusRequest, TenantConfigResponse, UpdateConfigRequest
)
from app.models.user import User
from app.services.tenant import tenant_service
from app.utils.response import ResponseUtil

router = APIRouter()


@router.get("/", summary="获取租户列表", response_model=TenantListResponse)
async def get_tenants(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    status_filter: Optional[bool] = Query(None, description="状态过滤"),
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """分页获取租户列表"""
    try:
        filters = {}
        if keyword:
            filters["keyword"] = keyword
        if status_filter is not None:
            filters["status"] = status_filter

        tenants, total = await tenant_service.get_tenants_with_pagination(
            db=db,
            page=page,
            page_size=page_size,
            filters=filters
        )

        return TenantListResponse(total=total, items=tenants)
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取租户列表失败: {str(e)}"
        )


@router.post("/", summary="创建租户")
async def create_tenant(
    tenant_data: TenantCreate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """创建新租户"""
    try:
        tenant = await tenant_service.create_tenant(
            db=db,
            obj_in=tenant_data.model_dump()
        )
        return ResponseUtil.success(data=tenant, message="租户创建成功")
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建租户失败: {str(e)}"
        )


@router.get("/{tenant_id}", summary="获取租户详情")
async def get_tenant(
    tenant_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """根据ID获取租户详情"""
    try:
        tenant = await tenant_service.get(db, id=tenant_id)
        if not tenant:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )

        # 获取统计信息
        stats = await tenant_service.get_tenant_statistics(db, tenant_id=tenant_id)

        tenant_data = {
            "id": tenant.id,
            "name": tenant.name,
            "code": tenant.code,
            "contact_user": tenant.contact_user,
            "contact_phone": tenant.contact_phone,
            "contact_email": tenant.contact_email,
            "address": tenant.address,
            "description": tenant.description,
            "logo": tenant.logo,
            "domain": tenant.domain,
            "status": tenant.status,
            "expire_time": tenant.expire_time,
            "package_id": tenant.package_id,
            "config": tenant.config,
            "created_at": tenant.created_at.isoformat() if tenant.created_at else None,
            "updated_at": tenant.updated_at.isoformat() if tenant.updated_at else None,
            "user_count": stats.get("user_count", 0),
            "dept_count": stats.get("dept_count", 0)
        }

        return ResponseUtil.success(data=tenant_data)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取租户详情失败: {str(e)}"
        )


@router.put("/{tenant_id}", summary="更新租户")
async def update_tenant(
    tenant_id: int,
    tenant_data: TenantUpdate,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新租户信息"""
    try:
        # 获取租户
        tenant = await tenant_service.get(db, id=tenant_id)
        if not tenant:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )

        # 更新租户
        updated_tenant = await tenant_service.update_tenant(
            db=db,
            db_obj=tenant,
            obj_in=tenant_data.model_dump(exclude_unset=True)
        )
        return ResponseUtil.success(data=updated_tenant, message="租户更新成功")
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新租户失败: {str(e)}"
        )


@router.delete("/{tenant_id}", summary="删除租户")
async def delete_tenant(
    tenant_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """删除租户"""
    try:
        tenant = await tenant_service.get(db, id=tenant_id)
        if not tenant:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )

        # 检查租户下是否有用户
        stats = await tenant_service.get_tenant_statistics(db, tenant_id=tenant_id)
        if stats.get("user_count", 0) > 0:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"该租户下有 {stats['user_count']} 个用户，无法删除"
            )

        # 软删除
        success = await tenant_service.delete(db, id=tenant_id)
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )
        return ResponseUtil.success(message="租户删除成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"删除租户失败: {str(e)}"
        )


@router.put("/{tenant_id}/status", summary="更新租户状态")
async def update_tenant_status(
    tenant_id: int,
    status_data: UpdateStatusRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """启用或禁用租户"""
    try:
        tenant = await tenant_service.get(db, id=tenant_id)
        if not tenant:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )

        updated_tenant = await tenant_service.update_status(
            db=db,
            tenant=tenant,
            status=status_data.status
        )
        return ResponseUtil.success(data=updated_tenant, message="租户状态更新成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新租户状态失败: {str(e)}"
        )


@router.get("/{tenant_id}/config", summary="获取租户配置", response_model=TenantConfigResponse)
async def get_tenant_config(
    tenant_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取租户配置信息"""
    try:
        config = await tenant_service.get_tenant_config(db, tenant_id=tenant_id)
        if config is None:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )
        return TenantConfigResponse(tenant_id=tenant_id, config=config)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取租户配置失败: {str(e)}"
        )


@router.put("/{tenant_id}/config", summary="更新租户配置")
async def update_tenant_config(
    tenant_id: int,
    config_data: UpdateConfigRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """更新租户配置信息"""
    try:
        tenant = await tenant_service.update_tenant_config(
            db=db,
            tenant_id=tenant_id,
            config=config_data.config
        )
        if not tenant:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )
        return ResponseUtil.success(data=tenant, message="租户配置更新成功")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"更新租户配置失败: {str(e)}"
        )


@router.get("/{tenant_id}/statistics", summary="获取租户统计信息")
async def get_tenant_statistics(
    tenant_id: int,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """获取租户统计信息"""
    try:
        tenant = await tenant_service.get(db, id=tenant_id)
        if not tenant:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="租户不存在"
            )

        stats = await tenant_service.get_tenant_statistics(db, tenant_id=tenant_id)
        return ResponseUtil.success(data=stats)
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取租户统计信息失败: {str(e)}"
        )